
const { Op } = require('sequelize')
const Cart = require('../model/Cart.model')
const Goods = require('../model/goods.model')

class Cartservice {
    async createOrUpdate(user_id, goods_id) {
        // 查找是否存在在这个数据
        const res = await Cart.findOne({
            where: {
                [Op.and]: {
                    user_id,
                    goods_id
                }
            }
        })
        if (res) {
            // 存在记录 number+1
            const incrementResult = await res.increment("number", { by: 1 })
            return await res.reload()
        } else {
            return await Cart.create({
                user_id: user_id,
                goods_id: goods_id
            })

        }
    }

    async findCarts(pageNum, pageSize) {
        const offset = (pageNum - 1) * pageSize
        // 获取总数
        // const count = Cart.count()
        // 获取分页具体数据
        // const rows = await Cart.findAll({ offset: offset, limit: pageSize * 1 })
        // 连表查询
        const { count, rows } = await Cart.findAndCountAll({
            attributes: ['id', 'goods_id', 'number', 'selected'],
            offset: offset,
            limit: pageSize * 1,
            include: {
                model: Goods, as: 'goods_info',
                attributes: ['goods_name', 'id', 'goods_price', 'goods_img'],
            }
        })
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows
        }
    }
    async updateCarts(params) {
        const { id, number, selected } = params
        const res = await Cart.findByPk(id)
        if (!res) return ""
        number !== undefined ? (res.number = number) : ''
        if (selected !== undefined) {
            res.selected = selected
        }
        return await res.save()
    }
    // 移除购物车
    async removeCarts(ids) {
        return await Cart.destroy({
            where: {
                id: {
                    [Op.in]: ids
                }
            }
        })
    }
    // 全选
    async selectAllCarts(user_id) {
        return await Cart.update({ selected: true }, {
            where: {
                user_id,
            }
        })
    }
    // 取消全选
    async unSelectAllCarts(user_id) {
        return await Cart.update({ selected: false }, {
            where: {
                user_id,
            }
        })
    }
    // 总数
    async totalCarts(user_id) {
        return await Cart.count({
            where: {
                user_id,
            }
        })
    }
}

module.exports = new Cartservice()